import axios from 'axios'
import store from '../store'
import Cookie from 'js-cookie'

let baseURL = process.env.BASE_API
// 创建axios实例
let service = axios.create({
    // api 的 base_url
    baseURL: baseURL,
    // 请求超时时间
    timeout: 300000
})

if (Cookie.get('token')) {
    // 让每个请求携带 token 请根据实际情况自行修改
    service.defaults.headers['Authorization'] = 'Bearer ' + Cookie.get('token')
}
let count = 0
// 拦截请求
service.interceptors.request.use(
    config => {
        count++
        store.dispatch('UpdateLoading', true)
        return config
    },
    error => {
        count++
        store.dispatch('UpdateLoading', true)
        return Promise.reject(error)
    }
)

// 全局拦截响应
service.interceptors.response.use(
    response => {
        count--
        // 关闭Loading
        if (count <= 0) {
            store.dispatch('UpdateLoading', false)
        } else {
            store.dispatch('UpdateLoading', true)
        }
        return new Promise(resolve => {
            resolve(response.data)
        })
    },
    error => {
        count--
        if (count <= 0) {
            store.dispatch('UpdateLoading', false)
        } else {
            store.dispatch('UpdateLoading', true)
        }
        return Promise.reject(error)
    }
)
export default service
